import { fetchHome } from '../../services/home/home';
import { fetchAllProducts } from '../../services/product/fetchProducts';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    imgSrcs: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    searchValue: '',
  },

  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    this.init();
  },


  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    fetchHome().then(({ swiper }) => {
      this.setData({
        imgSrcs: swiper,
        pageLoading: false,
      });
      this.loadGoodsList();
    });
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList() {
    this.setData({ goodsListLoadStatus: 1 });

    try {
      const goodsList = await fetchAllProducts();
      this.setData({
        goodsList: goodsList,
        goodsListLoadStatus: 0,
      });
    } catch (err) {
      console.error('加载商品列表失败:', err);
      this.setData({ goodsListLoadStatus: 3 });
    }
  },

  goodListClickHandle(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    console.log('首页商品点击，商品ID:', spuId);
    wx.navigateTo({
      url: `/pages/goods/details/index?productId=${spuId}`,
    });
  },

  onSearchChange(e) {
    this.setData({
      searchValue: e.detail.value
    });
  },

  onSearchSubmit(e) {
    const searchValue = e.detail.value || this.data.searchValue;
    if (searchValue && searchValue.trim()) {
      wx.navigateTo({
        url: `/pages/goods/result/index?searchValue=${encodeURIComponent(searchValue.trim())}`
      });
    }
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },

  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    const { index: promotionID = 0 } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
});
